<script setup>
import ArticleList from '@/components/articleList.vue'
import { reactive, ref} from 'vue'
import {
    likeArticleApi,
    delArticleApi,
    modyfyArticleApi,
    getArticleApi,
    addArticleWatchApi,
    getNewArticleListApi,
} from '@/api/article.js'
import {useUserStore} from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router' 
const router = useRouter()

//获取登录用户信息
const userStore = useUserStore()
const userInfo = userStore.userInfo

//用作展示帖子列表
const showArticleList = reactive({
    articleList:[],
    pageInfo:{}
})
//一次请求获取到的帖子列表
const articleList = ref({})

getArticleList(0)
//获取帖子列表
async function getArticleList(page){
    try{
        const resp = await getNewArticleListApi(page)  
        if(resp.data.code === 200){
            articleList.value = resp.data.data.content
            if(articleList.value.length !== 0){
                showArticleList.pageInfo = resp.data.data.page
                articleList.value.forEach((article)=>{
                    showArticleList.articleList.push(article)
                })
            }
        } 
    }catch{
        console.log(e)
    }
}

//获取下一页数据
const getMoreArticle = async (pageInfo)=>{
    if(pageInfo.totalPages === 1 || pageInfo.number+1 >= pageInfo.totalPages){
        return
    }else{
        getArticleList(pageInfo.number+1) 
    } 
}

//点赞
const onClickLike=async(userId,postId)=>{
    try{
        await addArticleWatchApi(postId)
        await likeArticleApi(postId,userId)
        showArticleList.articleList = []
        const promises = [];
        const count = showArticleList.pageInfo.number+1
        for (let i = 0; i < count; i++) {
            promises.push(getArticleList(i));
        }
        await Promise.all(promises);
    }catch(e){
        ElMessage.error(e.message)
    }
}
//点击评论
const onClickComment = async (postId)=>{
    try{
        await addArticleWatchApi(postId)
        //进入帖子详情
         router.push({path:'/detailBox/article',query:{
            articleId : postId}})
    }catch(e){
        console.log(e)
    }
}

</script>
<template>
    <div>
        <div class="article-box">
            <ArticleList
            @clickLike="onClickLike"
            @queryList="getMoreArticle"
            @clickComment="onClickComment"
            :articleInfo="showArticleList"
            ></ArticleList> 
        </div>

    </div>
</template>
<style lang="scss" scoped>

</style>